<template>
  <div class="order-confirm-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container" v-loading="loading">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>订单确认</el-breadcrumb-item>
      </el-breadcrumb>

      <div v-if="!loading" class="confirm-content">
        <!-- 商品信息 -->
        <div class="goods-section">
          <h3 class="section-title">商品信息</h3>
          <div class="goods-list">
            <!-- 单商品 -->
            <div v-if="orderType === 'single'" class="goods-item">
              <img :src="getImageUrl(goodsDetail?.image)" class="goods-image" />
              <div class="goods-info">
                <h4 class="goods-name">{{ goodsDetail?.goodsName }}</h4>
                <p class="goods-desc">{{ goodsDetail?.desc }}</p>
                <div class="goods-meta">
                  <span class="goods-price">¥{{ goodsDetail?.price }}</span>
                  <span class="goods-quantity">× {{ quantity }}</span>
                </div>
              </div>
              <div class="goods-subtotal">
                ¥{{ (goodsDetail?.price * quantity).toFixed(2) }}
              </div>
            </div>

            <!-- 购物车商品 -->
            <div v-else>
              <div 
                v-for="item in cartGoods" 
                :key="item.cartId"
                class="goods-item"
              >
                <img :src="getImageUrl(item.picture)" class="goods-image" />
                <div class="goods-info">
                  <h4 class="goods-name">{{ item.goodsName }}</h4>
                  <p class="goods-desc">{{ item.desc }}</p>
                  <div class="goods-meta">
                    <span class="goods-price">¥{{ item.price }}</span>
                    <span class="goods-quantity">× {{ item.goodsNum }}</span>
                  </div>
                </div>
                <div class="goods-subtotal">
                  ¥{{ (item.price * item.goodsNum).toFixed(2) }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 优惠券选择 -->
        <div class="coupon-section">
          <h3 class="section-title">优惠券</h3>
          <div class="coupon-selector" @click="showCouponDialog = true">
            <template v-if="selectedCoupon">
              <div class="selected-coupon">
                <span class="coupon-name">{{ selectedCoupon.couponName }}</span>
                <span class="coupon-discount">-¥{{ calculateDiscount().toFixed(2) }}</span>
              </div>
            </template>
            <template v-else>
              <div class="no-coupon">
                <span>选择优惠券</span>
              </div>
            </template>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>

        <!-- 价格明细 -->
        <div class="price-section">
          <h3 class="section-title">价格明细</h3>
          <div class="price-detail">
            <div class="price-row">
              <span>商品总价：</span>
              <span>¥{{ originalPrice.toFixed(2) }}</span>
            </div>
            <div v-if="selectedCoupon" class="price-row discount">
              <span>优惠券：</span>
              <span>-¥{{ calculateDiscount().toFixed(2) }}</span>
            </div>
            <el-divider />
            <div class="price-row total">
              <span>实付金额：</span>
              <span class="final-amount">¥{{ finalPrice.toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <el-button 
            type="danger" 
            size="large" 
            :loading="submitting"
            @click="handleSubmit"
          >
            {{ submitting ? '提交中...' : `提交订单 ¥${finalPrice.toFixed(2)}` }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 优惠券选择对话框 -->
    <CouponSelectDialog 
      v-model="showCouponDialog"
      :order-amount="originalPrice"
      @select="handleCouponSelect"
    />

    <!-- 支付对话框 -->
    <PaymentDialog 
      v-model="showPaymentDialog" 
      :order="createdOrder"
      @success="handlePaymentSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getGoodsDetail } from '@/api/goods'
import { getCartList } from '@/api/cart'
import { submitOrder } from '@/api/order'
import { getFileUrl } from '@/api/file'
import { ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'
import CouponSelectDialog from '@/components/CouponSelectDialog.vue'
import PaymentDialog from '@/components/PaymentDialog.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const showCouponDialog = ref(false)
const showPaymentDialog = ref(false)

// 订单类型和数据
const orderType = ref('cart') // 'single' | 'cart'
const goodsDetail = ref(null)
const quantity = ref(1)
const cartGoods = ref([])

// 优惠券
const selectedCoupon = ref(null)
const createdOrder = ref(null)

// 计算原价
const originalPrice = computed(() => {
  if (orderType.value === 'single' && goodsDetail.value) {
    return goodsDetail.value.price * quantity.value
  } else {
    return cartGoods.value.reduce((sum, item) => sum + item.price * item.goodsNum, 0)
  }
})

// 计算优惠金额
const calculateDiscount = () => {
  if (!selectedCoupon.value) return 0

  const coupon = selectedCoupon.value
  const orderAmount = originalPrice.value

  if (coupon.couponType === '0') {
    // 满减券
    return orderAmount >= coupon.minAmount ? coupon.discountAmount : 0
  } else if (coupon.couponType === '1') {
    // 折扣券
    const discount = orderAmount * (1 - coupon.discountRate)
    return Math.min(discount, coupon.maxDiscountAmount)
  } else if (coupon.couponType === '2') {
    // 免费券
    return orderAmount
  }
  return 0
}

// 计算最终价格
const finalPrice = computed(() => {
  return Math.max(0, originalPrice.value - calculateDiscount())
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const goodsId = route.query.goodsId
    const goodsNum = route.query.goodsNum
    const from = route.query.from
    const items = route.query.items

    if (goodsId && goodsNum) {
      // 单商品订单
      orderType.value = 'single'
      quantity.value = parseInt(goodsNum)
      const data = await getGoodsDetail(parseInt(goodsId))
      goodsDetail.value = data
    } else if (from === 'cart' && items) {
      // 从购物车结算
      orderType.value = 'cart'
      const selectedItems = JSON.parse(items)
      
      // 获取完整的购物车数据
      const allCartData = await getCartList()
      
      // 筛选出选中的商品
      cartGoods.value = allCartData.filter(item => 
        selectedItems.some(si => si.goodsId === item.goodsId)
      ).map(item => {
        const selectedItem = selectedItems.find(si => si.goodsId === item.goodsId)
        return {
          ...item,
          goodsNum: selectedItem.goodsNum
        }
      })
    } else {
      // 购物车订单（兼容旧逻辑）
      orderType.value = 'cart'
      const data = await getCartList()
      // 只显示选中的商品
      cartGoods.value = (data || []).filter(item => item.checked)
      
      if (cartGoods.value.length === 0) {
        ElMessage.warning('请先选择要购买的商品')
        router.push('/cart')
        return
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
    router.push('/')
  } finally {
    loading.value = false
  }
}

// 选择优惠券
const handleCouponSelect = (coupon) => {
  console.log('handleCouponSelect 被调用，传入的优惠券:', coupon)
  selectedCoupon.value = coupon
  
  // 添加调试信息
  console.log('selectedCoupon.value 已更新为:', selectedCoupon.value)
  
  if (coupon) {
    console.log('优惠券名称:', coupon.couponName)
    console.log('优惠券类型:', coupon.couponType)
    console.log('订单金额:', originalPrice.value)
    console.log('计算的优惠金额:', calculateDiscount())
  } else {
    console.log('取消选择优惠券')
  }
}

// 提交订单
const handleSubmit = async () => {
  submitting.value = true
  try {
    const params = {}
    
    // 单商品订单
    if (orderType.value === 'single') {
      params.goodsId = parseInt(route.query.goodsId)
      params.goodsNum = quantity.value
    }
    
    // 添加优惠券
    if (selectedCoupon.value) {
      params.userCouponId = selectedCoupon.value.userCouponId
    }

    // 提交订单，获取返回的订单ID
    const orderId = await submitOrder(params)
    console.log('订单提交成功，订单ID:', orderId)
    
    ElMessage.success('订单提交成功')
    
    // 使用真实的订单ID创建订单对象（用于支付）
    createdOrder.value = {
      id: orderId, // 使用后端返回的真实订单ID
      price: finalPrice.value,
      payNum: orderType.value === 'single' ? quantity.value : cartGoods.value.reduce((sum, item) => sum + item.goodsNum, 0),
      discountAmount: selectedCoupon.value ? calculateDiscount() : 0
    }
    
    console.log('创建的订单对象:', createdOrder.value)
    
    // 显示支付对话框
    showPaymentDialog.value = true
    
  } catch (error) {
    console.error('提交订单失败:', error)
  } finally {
    submitting.value = false
  }
}

// 支付成功
const handlePaymentSuccess = () => {
  router.push('/my-orders')
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}

onMounted(() => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  loadData()
})
</script>

<style scoped>
.order-confirm-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.confirm-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goods-section,
.coupon-section,
.price-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.goods-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.goods-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.goods-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
}

.goods-desc {
  font-size: 14px;
  color: #999;
  margin: 0 0 10px 0;
}

.goods-meta {
  display: flex;
  gap: 15px;
}

.goods-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: 500;
}

.goods-quantity {
  font-size: 14px;
  color: #666;
}

.goods-subtotal {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
  align-self: center;
}

.coupon-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.coupon-selector:hover {
  border-color: #409eff;
}

.selected-coupon {
  display: flex;
  gap: 10px;
}

.coupon-name {
  color: #333;
  font-weight: 500;
}

.coupon-discount {
  color: #ff4d4f;
  font-weight: bold;
}

.no-coupon {
  color: #999;
}

.arrow-icon {
  color: #ccc;
}

.price-detail {
  padding: 0;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 16px;
}

.price-row.discount {
  color: #ff4d4f;
}

.price-row.total {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.final-amount {
  font-size: 24px;
  color: #ff4d4f;
}

.submit-section {
  text-align: center;
  padding: 30px 0;
}

.submit-section .el-button {
  width: 300px;
  height: 50px;
  font-size: 18px;
}

@media (max-width: 768px) {
  .goods-item {
    flex-direction: column;
  }

  .goods-meta {
    justify-content: space-between;
  }

  .submit-section .el-button {
    width: 100%;
  }
}
</style>
